package com.niiwoo.civet.trade.listener;


import com.alibaba.fastjson.JSON;
import com.niiwoo.civet.trade.constant.MqConstant;
import com.niiwoo.civet.trade.dto.response.WithholdResultDTO;
import com.niiwoo.civet.trade.service.local.newRefund.dispatch.WithholdLocalService;
import com.niiwoo.tripod.provider.exception.BizException;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 代扣相关监听
 * @author wangjun
 */
@Slf4j
@Component
public class WithholdListener
{

    @Autowired
    protected WithholdLocalService withholdLocalService;

    protected void doAckAnwser(Message message, Channel channel,boolean isAck) throws IOException
    {
        if (isAck) {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } else {
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
        }
    }


    /**
     * 代扣结果接收事件
     * @param message
     * @param channel
     */
    @RabbitListener(queues = {MqConstant.WITHHOLD_APPLY_DATAREULST_QUEUE})
    public void withholdResult(Message message, Channel channel) throws IOException
    {
        //应答标记
        Boolean isAck = true;
        WithholdResultDTO withholdResultDTO = null;
        try
        {
            withholdResultDTO = JSON.parseObject(new String(message.getBody(), "UTF-8"),WithholdResultDTO.class);
            withholdLocalService.result(withholdResultDTO);
        }
        catch (BizException | IllegalArgumentException e )
        {
            log.error("WithholdListener ->withholdResult BizException:orderId={}",withholdResultDTO.getOrderId(), e);
        }
        catch (Exception e)
        {
            log.error("WithholdListener ->withholdResult exception:orderId={}", withholdResultDTO.getOrderId(),e);
            isAck = false;
            try
            {
                Thread.sleep(5 * 1000L);
            } catch (Exception expect) {}
        }
        finally
        {
            doAckAnwser(message,channel,isAck);
        }

    }

}
